import os
import time
import urllib3
import json
import shutil
import requests
import notify
import deploy_activity
import cdn_refresh

def save_activity_param(param):
    cwd = os.getcwd()
    keys = param.split(',')
    print("save_activity_param keys " + str(keys))
    with open(os.path.join(cwd, "activity.json"), "w") as f:
        f.write("\n".join(keys))

def load_update_activity():
    cwd = os.getcwd()
    activity = os.path.join(cwd, "activity.json")
    assets = []
    with open(activity, "r") as fr:
        lines = fr.readlines()
        for i in range(len(lines)):
            if (len(lines[i].strip()) > 0):
                assets.append(lines[i].strip().lower())
    print(assets)
    return assets

def sync_activity_to_release(param, url_config, download_activity_configs, context):
    save_activity_param(param)

    assets = load_update_activity()
    if (len(assets) == 0):
        print("activity.json = null")
        context["Status"]="deploy assets is null"
        notify.push_result(context)
        exit(0)
    
    response, configurls = download_activity_configs(assets)
    if len(response) > 0:
        sync_assets = {}
        android_assets = []
        ios_assets = []
        for resp in response:
            url = url_config["RELEASE"]["activity_url"]
            asset = resp[len(url):]
            splits = asset.split("/")
            print("asset " + asset + ", platform " + splits[1] + ", activity " + splits[2])
            if splits[1] == "Android":
                android_assets.append(splits[2])
            elif splits[1] == "iOS":
                ios_assets.append(splits[2])
        sync_assets["Android"] = android_assets
        sync_assets["iOS"] = ios_assets
        print("sync assets:\n" + str(sync_assets))
        deploy_activity.deploy(sync_assets, context)

    # check sync assets
    time.sleep(10)
    cdnurls = check_activity_assets(assets, configurls, url_config, context)

    # check webconfig
    check_activity_webconfig(assets, url_config, context)

    # push cdn
    cdn_refresh.push(cdnurls)

def check_activity_config(param, compare_config, context):
    save_activity_param(param)

    activity_configs = ["CF_AndroidActivityConfig", "CF_iOSActivityConfig"]
    result = compare_config(activity_configs, True)

    assets = load_update_activity()
    checkResult = {}
    for key in activity_configs:
        print("activity_configs check key " + key)
        itemResult = []
        checkResult[key] = itemResult
        items = result[key]
        for item in items:
            field = item["field"][1:]
            item["field"] = field
            print("item : " + json.dumps(item) + ", field " + field)
            if field in assets:
                itemResult.append(item)
    print("finished check_activity_config:\n" + json.dumps(checkResult))
    f=open("check_activity_config_result.txt","w")
    f.writelines(json.dumps(checkResult))
    f.close()

    status = True
    for key in activity_configs:
        if len(checkResult[key]) > 0:
            status = False
            break
    if status:
        context["Status"] = "Success"
    else:
        context["Status"] = "Fail"
    notify.push_result(context)

def check_activity_webconfig(assets, url_config, context):
    cwd = os.getcwd()
    web_config = {
        url_config["TEST"]["activity_cfg_url"]: os.path.join(cwd, "temp/test/test_web_activity.json"),
        url_config["RELEASE"]["activity_cfg_url"]:os.path.join(cwd, "temp/test/release_web_activity.json")
    }

    load_web_config_count = 0
    http = urllib3.PoolManager()
    for (url, localPath) in web_config.items():
        print("url: " + url)
        r = http.request('GET', url)
        if r.status == 200:
            # resp = r.data.decode('unicode_escape')
            # print(resp)
            print("save path " + localPath)
            with open(localPath, "wb") as fwriter:
                fwriter.write(r.data)
                fwriter.flush()
                load_web_config_count = load_web_config_count + 1
    if load_web_config_count != 2:
        print("\nError: download web_config fail")
        context["Status"]="download web_config fail"
        notify.push_result(context)
        exit(0)

    config = None
    with open(web_config[url_config["RELEASE"]["activity_cfg_url"]], "rb") as f2:
        config = json.load(f2)
    data = config["data"]
    for obj in data:
        content = obj["content"]
        for (id, item) in content.items():
            key = str(item["type"]).lower()
            if key in assets:
                assets.remove(key)
    extra = {"collect", "couponposter", "couponpostericon"}
    for key in extra:
        if key in assets:
            assets.remove(key)
    print("check web config result " + str(assets))
    if len(assets) > 0:
        context["Status"]="check web config not match: " + str(assets)
        notify.push_result(context)
    else:
        context["Status"]="check web config Success"
        notify.push_result(context)

def check_activity_assets(assets, configurls, url_config, context):
    print("check_activity_assets:")

    sync_assets = []
    print("configurls:\n " + str(configurls))

    http = urllib3.PoolManager()
    for (url, localpath) in configurls.items():
        if not os.path.exists(localpath):
            print("not exist " + localpath)
            r = http.request('GET', url)
            if r.status == 200:
                print("load file save to " + localpath)
                with open(localpath, "wb") as fwriter:
                    fwriter.write(r.data)
                    fwriter.flush()

    for (url, localpath) in configurls.items():
        if os.path.exists(localpath):
            print("exist " + localpath)
            with open(localpath, "rb") as freader:
                data = json.load(freader)

                platform = None
                if "Android" in localpath:
                    platform = "Android"
                elif "iOS" in localpath:
                    platform = "iOS"
                
                assetpath = localpath[localpath.find(platform):]
                assetpath = assetpath.replace("\\", "/")
                print(assetpath)
                assetdir = os.path.dirname(assetpath)

                sync_assets.append(assetpath)
                for (k, v) in data.items():
                    if isinstance(v, dict):
                        if "path" in v.keys():
                            sync_assets.append(assetdir + "/" + k + "/" +  os.path.basename(v["path"]))
                        else:
                            for (k1, v1) in v.items():
                                if isinstance(v1, dict):
                                    if "path" in v1.keys():
                                        sync_assets.append(assetdir + "/" + k + "/" +  os.path.basename(v1["path"]))
                    else:
                        sync_assets.append(assetdir + "/" + k + "_" + str(v))
        else:
            print("check_activity_assets not exist: " + url + ", path: " + localpath)
            exit(0)
    print("sync assets:\n" + str(sync_assets))

    cdnurls = []
    awscdn = url_config["AWSCDN"]
    aliyuncdn = url_config["AliyunCDN"]

    result = []
    for key in sync_assets:
        assetUrl = url_config["RELEASE"]["activity_url"] + "/" + key
        aliyunUrl = assetUrl.replace(awscdn, aliyuncdn)
        cdnurls.append(aliyunUrl)
        # print("asseturl " + assetUrl + ", aliyunUrl " + aliyunUrl)

        r = requests.get(aliyunUrl , stream=True)
        print(aliyunUrl + "  status_code:" + str(r.status_code))
        if r.status_code != 200:
            result.append(key)

    if len(result) > 0:
        print("check activity fail:\n " + str(result))
        context["Status"] = "sync_activity_assets Fail"
    else:
        print("check activity success")
        context["Status"] = "sync_activity_assets Success"
    notify.push_result(context)
    return cdnurls
